#!/usr/env python
import serial

def checksum(packet):
  return 0xFF-(sum(packet)&0xFF)

def pack_frame(frame):
  pack = [0x7e, 0x00, len(frame)]
  pack.extend(frame)
  pack.append(checksum(frame))
  return pack

def pack_and_send_frame(frame):
  outstr = ''.join([chr(c) for c in pack_frame(frame)])
  xbee.write(outstr)

def prepare_send(data_string, dest64, dest16=0xFFFE, command=0x10 ):
  frameid = 0x01
  broadcast_radius, options = 0, 0
  data_bin = [ord(c) for c in data_string]
  d = [command, frameid] + hex_to_list(dest64) + hex_to_list(dest16, 2)
  d.extend([broadcast_radius, options])
  d.extend(data_bin)
  pack = pack_frame(d)
  #print [hex(p) for p in pack]
  return pack

def hex_to_list(h, numbytes=8):
  '''Return a list of numbers for each byte in h'''
  return [(h>>i*8)&0xff for i in range(numbytes-1,0-1,-1)]

def send_to_coordinator(text):
  #for c in prepare_send(text, 0):
    #xbee.write(chr(c))
    str = ''.join([chr(c) for c in prepare_send(text,0)])
    xbee.write(str)

def init_xbee(port='/dev/ttyUSB1'):
  xbee.port = port
  xbee.baudrate = 38400
  xbee.open()



xbee = serial.Serial()
#data_to_send = "Hello World"
data_to_send = "Tx2Coord"
add64 = [0,0,0,0,0,0,0,0] # coordinator
#prepare_send(data_to_send, 0)

init_xbee()
send_to_coordinator("\n\rHELLO ! This is Einherjer speaking from the Python library\n\r")

xbee.close()
